package com.hronline;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import yaochangwei.pulltorefreshlistview.widget.RefreshableListView;
import yaochangwei.pulltorefreshlistview.widget.RefreshableListView.OnUpdateTask;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

import com.adapter.ManagerDashboardAdapter;
import com.delegate.ManagerDashBoardDelegate;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.models.Item;
import com.models.ManagerSummary;
import com.models.Notif;
import com.models.SectionItem;
import com.models.Status;
import com.parser.ManagerParser;

public class ManagerDashboardActivity extends Fragment implements Observer {

	ArrayList<Item> arrData	=	new  ArrayList<Item>();
	ManagerDashboardAdapter adapter;
	
	ProgressDialog loadingDialog;
	Context context;
	ManagerDashBoardDelegate delegate;
	
	private BroadcastReceiver mReceiver;
	
	public ManagerDashboardActivity(Context context, ManagerDashBoardDelegate delegate){
		super();
		this.context 	= 	context;
		this.delegate	=	delegate;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View fragmentView = inflater.inflate(R.layout.activity_manager_dashboard, container, false);
		
		createNavigationBar(fragmentView);
		
		/* get the control */
		RefreshableListView listView	=	(RefreshableListView)fragmentView.findViewById(R.id.refreshablelistview);	
		adapter	=	new ManagerDashboardAdapter(this.context, arrData);
		listView.setAdapter(adapter);
		listView.setOnUpdateTask(new OnUpdateTask() {
			
			@Override
			public void updateUI() {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void updateBackground() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onUpdateStart() {
				// TODO Auto-generated method stub
				refreshData();
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				handleClickOnNotificationItem(arg2);
			}
		});
		
		
		loadingDialog	=	new ProgressDialog(this.context);
		loadingDialog.setMessage(Constant.LOADING_STRING);
		
		/* create receiver */
		if(this.mReceiver == null){
			IntentFilter intentFilter	=	new IntentFilter(Constant.MUST_UPDATE_DASHBOARD);
			mReceiver	=	new BroadcastReceiver() {
				
				@Override
				public void onReceive(Context context, Intent intent) {
					// TODO Auto-generated method stub
					refreshData();
				}
			};
			
			this.context.registerReceiver(mReceiver, intentFilter);
		}

		/* call api to get data */
		if(this.arrData.size() == 0){
			getManagerSummary();
		}
		
		
        return fragmentView;
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		this.context.unregisterReceiver(mReceiver);
	}
	
	/* ================================================================== */
	
	/* INIT VIEW
	 * this section is used to create view for this activity 
	 * */
	
	/* this method is used to create navigation bar */
	private void createNavigationBar(View view){
		
		TextView txtManagerDashboardTitle	=	(TextView)view.findViewById(R.id.txtManagerDashboardTitle);
		ImageButton btnUserInfo				=	(ImageButton)view.findViewById(R.id.btnUserInfo);
		ImageButton btnOrganization			=	(ImageButton)view.findViewById(R.id.btnOrganization);
		
		/* assign selector */
		txtManagerDashboardTitle.setText(Constant.currentUser.getFullName());
		btnUserInfo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				openUserInfoPage();
			}
		});
		
		
		btnOrganization.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				openOrganizationPage();
			}
		});
	}
	
	/* ================================================================== */
	
	/* SELECTOR
	 * This section is used to create selector to handle for this activity
	 *  */
	
	/* this method is used to handle when user click on user info button */
	private void openUserInfoPage(){
		
	}
	
	/* this method is used to handle when user click on organization button */
	private void openOrganizationPage(){
		
	}
	
	
	
	/* remove all data to refresh the new one */
	private void refreshData(){
		getManagerSummary();
	}
	
	/* this method is used to handle when user click on the item on list view */
	private void handleClickOnNotificationItem(int position){
		if(position - 1 > 1){// check the item list is notification item
			Notif item	=	(Notif)arrData.get(position - 1);
			handleNotifClick(item);
		}
	}
	
	/* handle notification click  */
	private void handleNotifClick(Notif item){
		switch (item.getType()) {
		case 0:
			openRequestAbsencePage(item.getAbsenceId());
			break;
			
		case 1:
			openLogSicknessPage(item.getAbsenceId());
			break;
			
		case 4:
			openApproveAbsencePage(item.getAbsenceId());
			break;
		}
	}
	
	/* open request absence page */
	private void openRequestAbsencePage(String absenceID){
		
//		Intent intent	=	new Intent(this, RequestAbsenceActivity.class);
//		intent.putExtra("AbsenceID", absenceID);
//		this.startActivity(intent);
		
	}
	
	/* open approve asbsence page */
	private void openApproveAbsencePage(String absenceID){
		
//		Intent intent	=	new Intent(this, ApproveAbsenceDetailActivity.class);
//		intent.putExtra("AbsenceID", absenceID);
//		this.startActivity(intent);
		
	}
	
	/* open log sickness page */
	private void openLogSicknessPage(String absenceID){
		
//		Intent intent	=	new Intent(this, LogSicknessActivity.class);
//		intent.putExtra("AbsenceID", absenceID);
//		this.startActivity(intent);
		
	}
	
	/* ================================================================== */
	
	/* CALLING API
	 * This section is used to create method call API to get data from server
	 *  */
	
	/* this method is used to get manager summary information */
	private void getManagerSummary(){
		arrData.clear();
		adapter.arrItem.clear();
		adapter.notifyDataSetChanged();
		loadingDialog.show();
		
		String url	=	String.format("%sSummary/GetManagerSummary?AuthorisationToken=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN);
		
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.get(url, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				handleGetManagerSummarySuccess(content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				handleConnectionFail();
			}
		});
	}
	
	/* this method is used to get today notification */
	private void getTodayNotification(){
		String url	=	String.format("%sSummary/GetNotifications?AuthorisationToken=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN);
		
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.get(url, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				handleGetTodayNotificationSuccess(content);
			}
			
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				
				handleConnectionFail();
			}
			
		});
	}
	
	/* ================================================================== */
	
	/* HANDLE CALLING API 
	 * this section is used to handle when calling API finish
	 * */
	
	/* this method is used to handle when finish call get manager summary successfully */
	private void handleGetManagerSummarySuccess(String dataContent){
		
		/* parsing data */
		ArrayList<Object> arrResult	=	ManagerParser.parseManagerSummary(dataContent);
		
		/* get status object */
		Status statusItem	=	(Status)arrResult.get(0);
		if(!isStatusError(statusItem, "getManagerSummary")){
			
			ManagerSummary managerSummaryItem	=	(ManagerSummary)arrResult.get(1);
			arrData.add(managerSummaryItem);
			adapter.arrItem	=	arrData;
			
			/* call api to get notification today */
			getTodayNotification();
		}
	}
	
	/* this method is used to handle when finish call get today notification successfully */
	private void handleGetTodayNotificationSuccess(String dataContent){
		/* parsing data */
		ArrayList<Object> arrResult	=	ManagerParser.parseTodayNotification(dataContent);
		
		/* get status object */
		Status statusItem	=	(Status)arrResult.get(0);
		if(!isStatusError(statusItem, "getTodayNotifications")){
			
			@SuppressWarnings("unchecked")
			ArrayList<Item> arrNotification	=	(ArrayList<Item>)arrResult.get(1);
			arrData.add(new SectionItem("Today's Notifications"));
			arrData.addAll(arrNotification);
			adapter.arrItem	=	arrData;
			adapter.notifyDataSetChanged(); //reload data
			loadingDialog.dismiss();
		}
	}
	
	/* this method is used to handle when call get manager summary fail */
	private void handleConnectionFail(){
		
		loadingDialog.dismiss();
		Constant.showErrorMessage(this.context, Constant.CANNOT_CONNECT_SERVER);
	}
	
	private boolean isStatusError(Status statusItem, String apiCalling){
		
		/* dismiss the loading dialog */
		loadingDialog.dismiss();
		
		if(statusItem.statusCode >= Constant.IVALID_AUTHORIZED_TOKEN){
			String message	=	String.format("%s - API %s", statusItem.getStatusText(), apiCalling);
			
			AlertDialog.Builder builder	=	new AlertDialog.Builder(this.context);
			builder.setMessage(message);
			builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					delegate.openLoginPage();
				}
			});
			
			builder.show();
			
			return true;
		}
		
		return false;
	}

	/* ================================================================= */
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		
	}
}
